<?php

namespace app\store\controller\order;

use app\common\controller\Backend;
use think\Db;

/**
 * 订单商品管理
 *
 * @icon fa fa-circle-o
 */
class Goods extends Backend
{

    /**
     * Goods模型对象
     * @var \app\store\model\order\Goods
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\store\model\order\Goods;
        $this->view->assign("refundStatusList", $this->model->getRefundStatusList());
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("stateList", $this->model->getStateList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            $_where = [];
            if ($this->request->get("user_id")) {
                $_where = ['order.user_id'=>$this->request->get("user_id")];
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            //var_dump($where);
            $list = $this->model
                ->with('order,shop,sku')
                ->where($where)
                ->where($_where)
                ->where('gdtype', '=', 0)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $row) {


            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 查看
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function detail($ids = null)
    {
        $row = $this->model->get($ids);

        $row['address'] = model('app\store\model\order\Address')
            ->where(['order_id' => $row['order_id']])
            ->order('isaddress desc')
            ->field('id,name,mobile,address,address_name')
            ->find();

        $row['pay'] = model('app\store\model\wanlshop\Pay')
            ->where(['order_id' => $row['order_id'], 'type' => 'goods'])
            ->find();

        $row['user'] = Db::name('user')
            ->where(['id' => $row['order']['user_id']])
            ->field('id,nickname,username,mobile')
            ->find();

        $row['info'] = Db::name('wanlshop_order_goods')
            ->where(['order_id' =>  $row['order_id']])
            ->select();

        // 查询快递状态
        switch ($row['order']['state']) {
            case 1:
                $express = [
                    'context' => '付款后，即可将宝贝发出',
                    'status' => '提交订单',
                    'time' => date('Y-m-d H:i:s', $row['order']['createtime'])
                ];
                break;
            case 2:
                $express = [
                    'context' => '商家正在处理订单',
                    'status' => '已付款',
                    'time' => date('Y-m-d H:i:s', $row['order']['paymenttime'])
                ];
                break;
            case 3:
                $express = [
                    'status' => '已发货',
                    'context' => '包裹正在等待快递小哥揽收~',
                    'time' => date('Y-m-d H:i:s', $row['order']['delivertime'])
                ];
                break;
            case 4:
                $express = [
                    'context' => '商家正在处理订单',
                    'status' => '已收货',
                    'time' => date('Y-m-d H:i:s', $row['order']['taketime'])
                ];
                break;
            case 6:
                $express = [
                    'context' => '商家正在处理订单',
                    'status' => '已完成',
                    'time' => date('Y-m-d H:i:s', $row['order']['dealtime'])
                ];
                break;
            default:
                $express = [
                    'context' => '商家正在处理订单',
                    'status' => '已取消',
                    'time' => date('Y-m-d H:i:s', $row['order']['dealtime'])
                ];
                break;

            // default: // 获取物流
            // 	$eData = model('app\api\model\wanlshop\KuaidiSub')
            // 		->where(['express_no' => $row['express_no']])
            // 		->find();
            // 	// 获取数据 兼容PHP7.4	1.1.5升级
            // 	if(!empty($eData['data'])){
            // 		$ybData = json_decode($eData['data'], true);
            // 		// 运单状态 1.0.6升级
            // 		$statusText = ['在途','揽收','疑难','签收','退签','派件','退回','转投'];
            // 		$status = $statusText[0];
            // 		if(in_array('status', $ybData[0])){
            // 			$status = $ybData[0]['status'];
            // 		}else{
            // 			if($eData['ischeck'] === 1){
            // 				$status = $statusText[3];
            // 			}else{
            // 				$status = $statusText[$eData['state']];
            // 			}
            // 		}
            // 		$express = [
            // 			'status' => $status,
            // 			'context' => $ybData[0]['context'],
            // 			'time' => $ybData[0]['time'],
            // 		];
            // 	}else{
            // 		$express = [
            // 			'status' => '已发货',
            // 			'context' => '包裹正在等待快递小哥揽收~',
            // 			'time' => date('Y-m-d H:i:s', $row['delivertime'])
            // 		];
            // 	}
        }




        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign("kuaidi", $express);
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        // $params = $this->request->post('row/a');
        // if (empty($params)) {
        //     $this->error(__('Parameter %s can not be empty', ''));
        // }
        // $params = $this->preExcludeFields($params);
        // $result = false;
        // Db::startTrans();
        // try {
        //     //是否采用模型验证
        //     if ($this->modelValidate) {
        //         $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
        //         $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
        //         $row->validateFailException()->validate($validate);
        //     }
        //     $result = $row->allowField(true)->save($params);
        //     Db::commit();
        // } catch (ValidateException|PDOException|Exception $e) {
        //     Db::rollback();
        //     $this->error($e->getMessage());
        // }
        // if (false === $result) {
        //     $this->error(__('No rows were updated'));
        // }
        // $this->success();
    }


    /**
     * 发货
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function deliver($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');

        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            $model = new \app\store\model\order\Order();
            $editlist = $model->where('id', $row['order_id'])->find();

            $param['express_name'] = $params['express_name'];
            $param['express_no'] = $params['express_no'];
            $param['delivertime'] = time();


            $result = $editlist->save($param);
            Db::commit();
        } catch (ValidateException | PDOException | Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    /**
     * 修改发货地址
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function address($ids = null)
    {
        $row = $this->model->get($ids);
        $row['address'] = model('app\store\model\order\Address')
            ->where(['order_id' => $row['order_id']])
            ->order('isaddress desc')
            ->field('id,name,mobile,address,address_name')
            ->find();
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');

        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            $model = new \app\store\model\order\Address();
            $editlist = $model->where('order_id', $row['order_id'])->find();

            $param['address'] = $params['address'];
            $param['isaddress'] = 1;
            $param['updatetime'] = time();


            $result = $editlist->save($param);
            Db::commit();
        } catch (ValidateException | PDOException | Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }



}
